﻿using System.Collections.Generic;
using System.Linq;

namespace Qy.Scenario;

public static partial class MenuExtensions
{

    /// <summary>
    /// 递归遍历类别列表并将其排序
    /// </summary>
    public static void IndentedCate(IEnumerable<Menu> docCats, IList<ViewMenu> treeModels, int parentId = 0, int depth = 0)
    {
        depth++;
        List<Menu> cates = docCats.Where(a => a.Pid == parentId).ToList();
        foreach (Menu item in cates)
        {
            ViewMenu treeModel = new()
            {
                Id = item.Id,
                Title = item.Name,
                Type = item.Type,
                Status = item.Status,
                Sort = item.Sort,
                Depth = depth,
                Spread = "true",
            };
            //if (item.Type == 1)
             //   treeModel.Disabled = "true";
            treeModels.Add(treeModel);
            IndentedCate(docCats, treeModel.Children, treeModel.Id, depth);
        }
    }
    /// <summary>
    /// 转换类别列表模型
    /// </summary>
    /// <returns></returns>
    public static IEnumerable<ViewMenu> AsViewCates(this IEnumerable<Menu>  docCats)
    {
        List<ViewMenu> treeModels = new();
        IndentedCate(docCats, treeModels);
        
        List<ViewMenu> outModels = new();
        foreach (var item in treeModels)
        {
            MegCate(outModels, item);
        }
        return outModels;
    }

    static void MegCate(IList<ViewMenu> outModels, ViewMenu cate)
    {
        outModels.Add(cate);
        foreach (var item in cate.Children)
        {
            item.ChildrenCount += item.Children.Count;
            MegCate(outModels, item);
        }
    }

    /// <summary>
    /// 类别列表 引用
    /// <returns></returns>
    public static IEnumerable<ViewMenu> AsCateListItems(this List<Menu> docCats)
    {
        List<ViewMenu> cate = new();
        IEnumerable<ViewMenu> categories = docCats.AsViewCates();
        for (int i = 0; i < categories.Count(); i++)
        {
            ViewMenu folder = categories.ElementAt(i);
            string headString = "";
            if (folder.Depth > 1)
            {
                if (folder.ChildrenCount > 0)
                    headString += "├ ";
                else
                    headString += "└ ";
                for (int j = 2; j < folder.Depth; j++)
                    headString += "─";
            }
            string selecttext = string.Format("{0}{1}", headString, folder.Title);
            
            cate.Add(new ViewMenu
            { 
                Id = folder.Id, 
                Pid = folder.Pid, 
                Title = selecttext,
                Sort = folder.Sort,
                Type = folder.Type,
                Status = folder.Status, 
                Depth = folder.Depth,
            });
        }
        return cate.ToList();
    }

}
